package com.yanqu.sync.demo.dispatcher;

import com.yanqu.sync.demo.entity.Request;
import com.yanqu.sync.demo.entity.Response;


import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class PendingCenter {

    private static final AtomicLong sequenceId = new AtomicLong();
    private static final Map<Long, Result> pendingMap = new ConcurrentHashMap<>();

    public static CompletableFuture<Response> send(Request request) {
        long l = sequenceId.incrementAndGet();
        request.setSequenceId(l);
        Result result = new Result();
        pendingMap.put(l, result);
        Service.clientSend(request);
        return result.getFuture();

//        try {
//            return result.get(1, TimeUnit.SECONDS);
//        } catch (InterruptedException | TimeoutException | ExecutionException e) {
//            Response response = new Response();
//            response.setErrorMessage(Arrays.toString(e.getStackTrace()));
//            return response;
//        } finally {
//            pendingMap.remove(l);
//        }
    }

    public static void receive(Response response) {
        Result result = pendingMap.remove(response.getSequenceId());
        if (result != null) {
            result.getFuture().complete(response);
        }
    }
}


